import sys
import os
import time
from pysqlite2 import dbapi2 as sqlite


connection = sqlite.connect('./database/keys.db')
cursor = connection.cursor()


def group_ips(rows):
	addresses = {}

	for row in rows:
		if not row[2] in addresses:
			addresses[row[2]] = [row[3]]
		else:
			addresses[row[2]].append(row[3])

	return addresses


def find_collisions(key):
	addresses = []
	keys = []

	if key.replace('.', '').isdigit():
		cursor.execute('SELECT * FROM session WHERE `address`=\'%s\'' % key)
	else:
		cursor.execute('SELECT * FROM session WHERE `key`=\'%s\'' % key)

	for row in cursor:
		if not row[2] in addresses:
			addresses.append(str(row[2]))

	for address in addresses:
		cursor.execute('SELECT * FROM session WHERE `address`=\'%s\'' % address)

		for row in cursor:
			if not row[1] in keys:
				keys.append(str(row[1]))

	return keys, addresses


if __name__ == '__main__':
	key = raw_input('Search key: ')

	keys, addresses = find_collisions(key)

	print keys
	print addresses